import time

from PyQt5.QtWidgets import (QApplication, QWidget
                             , QMessageBox, QComboBox,  QLineEdit,QDateEdit,QFileDialog,
                             QMenu, QToolButton, QInputDialog,QTableWidgetItem,QAbstractItemView,QHBoxLayout)
from PyQt5.QtCore import Qt,QDate,QDateTime
from PyQt5.QtGui import QIcon
from PyQt5.Qt import QSizePolicy,QSize

import sys
import os
from win32com import client
import threading
import shutil
import json
from functools import partial
import openpyxl
from forms.config import basePath,app_info,app_dist
from forms.component import 管理_基类,筛选条件,基础信息导入
from forms.component.progressWindow import progress,wrapper_progress
from forms.component.db import 操作_sql
from forms.component.下拉列表框 import ExtendedComboBox

class 管理窗口_基类(QWidget):
    def __init__(self):
        '''管理窗口的基类 '''
        super().__init__()
        self.parmsInit() #参数的基本设置
        # 定义筛选条件     筛选入库日期的开始和结束，搜索的条件
        self.search_text = {}
        self.initUi()

        # # 定义显示类型
        # self.show_class = 'toolButton_7'

    def parmsInit(self):
        self.tableName='办公室_账号'
        # # 定义筛选条件     筛选入库日期的开始和结束，搜索的条件
        # self.search_text = {'单据日期': {
        #     '开始日期': QDate.currentDate().addDays(-60).addYears(-1).toString('yyyy-MM-dd'),
        #     '结束日期': QDate.currentDate().addDays(30).toString('yyyy-MM-dd')
        # }
        # }
    def initUi(self):
        '''窗口的初始化'''
        self.ui = 管理_基类.Ui_Form()
        self.ui.setupUi(self)
        self.showActionIcon()#显示所有的图标
        self.showPrint() #显示所有的打印功能
        self.showPrintStyles() #显示所有的报表打印样式
        self.showTableWidgetDesigner() #显示tablewidget 数据信息 上一页下一页等

        # 显示类型改变
        self.ui.toolButton_7.clicked.connect(self.ShowChanged)
        self.ui.toolButton_8.clicked.connect(self.ShowChanged)

        # 筛选条件
        self.ui.toolButton_9.clicked.connect(self.SearchChanged)
        #导入导出文件
        self.ui.toolButton_10.clicked.connect(self.importFile)
        self.ui.toolButton_11.clicked.connect(self.exportTemplateFile)
        # 右键弹出菜单
        self.ui.tableWidget.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        # 右键槽函数
        self.ui.tableWidget.customContextMenuRequested.connect(partial(self._generateMenu, self.ui.tableWidget))

        #权限
        self.ui.toolButton_3.clicked.connect(self.Del_Btn_Clicked)
        self.ui.toolButton_4.clicked.connect(self.New_Btn_Clicked)
        self.ui.toolButton.clicked.connect(self.Updata_Btn_Clicked)
        self.ui.toolButton_2.clicked.connect(self.Show_Btn_Clicked)
        self.ui.toolButton_5.clicked.connect(self.Flash_Btn_Clicked)

        # self.权限控制()
        self.setWindowTitle(self.tableName)
    def _generateMenu(self, textedit, pos):
        # print(pos)
        # 转换屏幕的坐标系

        screenPos = self.sender().mapToGlobal(pos)
        # colNum, rowNum = -1, -1
        # for i in self.ui.tableWidget.selectionModel().selection().indexes():
        #     colNum = i.column()
        #     rowNum = i.row()
        # print('选中的单元格', i.column(), i.row())
        # if colNum == 6:
        tabWidget_menu = QMenu()
        sb_item = tabWidget_menu.addAction("导出数据-Excel")

        tabWidget_action = tabWidget_menu.exec(screenPos)  # 右键执行
        if tabWidget_action == sb_item:
            self.dataToExcel()
    def dataToExcel(self):

        fileName, ok = QFileDialog.getSaveFileName(self, "文件导出",
                                                   f"{basePath}/temp/导出数据-{QDateTime.currentDateTime().toString('yyyyMMddHHmmss')}",
                                                   "Text Files (*.xlsx);;All Files (*)")

        if ok:
            fileds = []
            for i in range(self.ui.tableWidget.columnCount()):
                fileds.append(self.ui.tableWidget.horizontalHeaderItem(i).text())

            workbook = openpyxl.Workbook(fileName)
            workbook.create_sheet('导出数据')
            workbook.save(fileName)
            workbook = openpyxl.load_workbook(fileName)
            worksheet = workbook['导出数据']
            worksheet.cell(1, 1, value=f'数据信息导出 {self.windowTitle()}')
            worksheet.merge_cells('A1:T1')

            for i in range(len(fileds)):
                worksheet.cell(2, i + 1, value=fileds[i])
            z = 0
            for i in range(self.ui.tableWidget.rowCount()):
                if not self.ui.tableWidget.isRowHidden(i):
                    for j in range(self.ui.tableWidget.columnCount()):
                        worksheet.cell(3 + z, j + 1, value=self.ui.tableWidget.item(i, j).text())
                    z += 1
                else:
                    continue
            # for i in range(len(data)):
            #     for j in range(len(fileds)):
            #         worksheet.cell(2 + i, j + 1, value=data[i][j])

            workbook.save(fileName)
            path = os.path.realpath(fileName)  # 获取的相对路径，并选中文件
            os.system(f'explorer /select,{path}')
    def importFile(self):
        '''导入文件'''
        pass
    def exportTemplateFile(self):
        '''导出模板文件'''
        pass
    def showTableWidgetDesigner(self):
        '''显示桌面控件设计'''

        self.ui.comboBox.addItems(['1', '10', '20', '30', '40', '50', '100', '200'])
        self.ui.comboBox.setCurrentText('20')
        self.page_row = int(self.ui.comboBox.currentText())  # 每页显示的行数
        self.current_page=1
        self.ui.comboBox_2.addItems([str(i) for i in range(1, 1000)])
        self.显示查询数据()

        # 单元格自适应
        self.ui.pushButton_7.clicked.connect(self.auto_)

        self.ui.pushButton_4.clicked.connect(lambda: self.Next_Btn_Clicked(self.current_page, self.items))
        self.ui.pushButton_3.clicked.connect(lambda: self.Next_Btn_Clicked(self.current_page - 2, self.items))
        self.ui.pushButton.clicked.connect(lambda: self.Next_Btn_Clicked(0, self.items))
        self.ui.pushButton_5.clicked.connect(lambda: self.Next_Btn_Clicked(len(self.items), self.items))
        self.ui.pushButton_6.clicked.connect(lambda: self.ALL_Btn_Clicked(0, self.items))
        self.ui.comboBox.currentTextChanged.connect(self.page_row_Changed)
        self.ui.comboBox_2.currentTextChanged.connect(self.page_count_Changed)
        self.ui.pushButton_2.clicked.connect(self.TextChanged)
        self.ui.lineEdit.returnPressed.connect(self.TextChanged)
    def ShowChanged(self):
        self.show_class = self.sender().objectName()
        self.ui.label_6.setText(f'当前选择的显示类型为{self.sender().text()}')

        self.显示查询数据()

    def SearchChanged(self):
        pass

    def 权限控制(self):
        if self.app.current_app_dist['权限信息'][f"{self.tableName}_新增"] == 0:
            self.ui.toolButton_4.setVisible(False)
        else:
            self.ui.toolButton_4.setVisible(True)
        if self.app.current_app_dist['权限信息'][f"{self.tableName}_删除"] == 0:
            self.ui.toolButton_3.setVisible(False)
        else:
            self.ui.toolButton_3.setVisible(True)
        if self.app.current_app_dist['权限信息'][f"{self.tableName}_更新"] == 0:
            self.ui.toolButton.setVisible(False)
        else:
            self.ui.toolButton.setVisible(True)
        if self.app.current_app_dist['权限信息'][f"{self.tableName}_查看"] == 0:
            self.ui.toolButton_2.setVisible(False)
        else:
            self.ui.toolButton_2.setVisible(True)
    def showPrint(self):
        '''显示所有的打印功能'''
        self.ui.toolButton_6.setPopupMode(QToolButton.MenuButtonPopup)
        self.ui.toolButton_6.clicked.connect(self.Print_Btn_Clicked)
        path= os.path.join(basePath ,"staticfiles","img")
        toolBtnMenu = QMenu()
        item_action = toolBtnMenu.addAction(QIcon(QIcon(os.path.join(path , 'h16.png'))), '打印预览', self.Print_Btn_Clicked)
        item_action.setObjectName('打印预览')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(os.path.join(path , 'h28.png'))), '报表设计', self.Print_Btn_Clicked)
        item_action.setObjectName('报表设计')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(os.path.join(path, 'h28.png'))), '打开报表所在位置',
                                            self.Print_Btn_Clicked)
        item_action.setObjectName('打开报表所在位置')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(os.path.join(path , 'h15.png'))), '新增打印样式', self.Print_Btn_Clicked)
        item_action.setObjectName('新增打印样式')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(os.path.join(path , 'h29.png'))), '设置默认样式', self.Print_Btn_Clicked)
        item_action.setObjectName('设置默认样式')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(os.path.join(path , 'h29.png'))), '删除打印样式', self.Print_Btn_Clicked)
        item_action.setObjectName('删除打印样式')
        self.ui.toolButton_6.setMenu(toolBtnMenu)
    def showPrintStyles(self):
        # 显示所有报表样式
        filename_List, path = self.getReportStyles() #获取所有样式
        self.ui.comboBox_3.addItems(filename_List)

        默认样式 = self.getReportDefaultStyle() #获取默认样式
        self.ui.comboBox_3.setCurrentText(默认样式)
    def showActionIcon(self):
        '''显示控件图标'''
        path = os.path.join(basePath ,"staticfiles","img")
        showicon=[(self.ui.toolButton,'h17.png'),
                  (self.ui.toolButton_2, 'h16.png'),
                  (self.ui.toolButton_3, 'h10.png'),
                  (self.ui.toolButton_4, 'h15.png'),
                  (self.ui.toolButton_5, 'h9.png'),
                  (self.ui.toolButton_6, 'h27.png'),
                  (self.ui.toolButton_7, 'h18.png'),
                  (self.ui.toolButton_8, 'h18.png'),
                  (self.ui.toolButton_9, 'h18.png'),
                  (self.ui.toolButton_10, 'h18.png'),
                  (self.ui.toolButton_11, 'h18.png'),
                  ]
        for item in showicon:
            item[0].setIcon(QIcon(os.path.join(path, item[1])))
            item[0].setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)







        #
        # self.setWindowTitle(self.window_title)
        # # self.进度条 = 进度条_窗体()
        # self.ui.comboBox.addItems(['1', '10', '20', '30', '40', '50', '100', '200'])
        # self.ui.comboBox.setCurrentText('20')
        # self.page_row = int(self.ui.comboBox.currentText())  # 每页显示的行数
        # self.ui.comboBox_2.addItems([str(i) for i in range(1, 5000)])
        # self.显示查询数据()
        # # 单元格自适应
        # self.ui.pushButton_7.clicked.connect(self.auto_)
    def getReportDefaultStyle(self):
        file_dir = self.tableName.split('_')
        默认样式 = app_dist.get('defaultReportStyles')
        for fi in file_dir:
            默认样式 = 默认样式.get(fi)
        默认样式 = 默认样式.get('总报表')
        return 默认样式
    def getReportStyles(self):
        '''获取所有报表样式'''
        path = os.path.join(basePath, 'report', *self.tableName.split('_'), '总报表')
        # 先判断是否为一个文件夹，然后在判断里面有多少文件
        filename_List = []
        if os.path.isdir(path):
            for pat in os.listdir(path):
                if os.path.isfile(os.path.join(path , pat)):
                    fileName = os.path.splitext(pat)
                    if fileName[1] == '.grf':
                        filename_List.append(fileName[0])
        return filename_List, path

    def Print_Btn_Clicked(self):
        '''打印功能toolBtn单击事件'''
        if self.sender().objectName() == '设置默认样式':
            file_dir = self.tableName.split('_')
            设置默认样式 = app_dist.get('defaultReportStyles')
            for fi in file_dir:
                设置默认样式 = 设置默认样式[fi]

            默认样式 = self.ui.comboBox_3.currentText()
            设置默认样式['总报表'] = 默认样式

            with open(os.path.join(basePath, 'my.json'), 'w', encoding='utf8') as fp:
                json.dump(app_dist,fp,ensure_ascii=False)

            QMessageBox.information(self, '提示', '设置成功')
        elif self.sender().objectName() == '新增打印样式':
            name, ok = QInputDialog.getText(self, '创建', '请输入创建的样式名称:')
            # print(name,ok)
            if name and ok:
                filename_List, path = self.getReportStyles()
                if name not in filename_List:
                    # print("创建成功",path,name)
                    if len(filename_List) != 0:
                        shutil.copy(os.path.join(path , filename_List[0] + '.grf'), os.path.join(path , name + '.grf'))
                        # os.startfile(path+name+'.grf')
                        os.system(f"explorer /select,{os.path.join(path , name + '.grf')}")
                    else:
                        filename=os.path.join(path , name+'.grf')
                        with open(filename, 'w') as f:
                            f.write('''{
                                "Version":"6.8.5.3",
                                "Font":{
                                    "Name":"宋体",
                                    "Size":105000,
                                    "Weight":400,
                                    "Charset":134
                                },
                                "Printer":{
                                },
                                "ReportHeader":[
                                    {
                                        "Name":"ReportHeader1"
                                    }
                                ]
                            }''')
                        os.system(f"explorer /select,{filename}")
                    self.ui.comboBox_3.addItem(name)
                else:
                    QMessageBox.information(self, '提示', '样式名称重复')
        elif self.sender().objectName() == '删除打印样式':
            name, ok = QInputDialog.getText(self, '删除', '请谨慎删除，如删除请输入删除密码', QLineEdit.Password)

            if name == '123456' and ok:
                filename_List, path = self.getReportStyles()
                name = self.ui.comboBox_3.currentText()
                if name not in filename_List:
                    QMessageBox.information(self, '提示', '找不到删除文件')

                else:
                    try:
                        os.remove(os.path.join(path , name + '.grf'))

                        self.ui.comboBox_3.removeItem(self.ui.comboBox_3.currentIndex())
                        QMessageBox.information(self, '提示', '删除成功')
                    except:
                        QMessageBox.information(self, '提示', '删除异常')
            elif ok:
                QMessageBox.information(self, '提示', '密码错误')

        elif self.sender().objectName() == '报表设计':

            filename_List, path = self.getReportStyles()
            # print(filename_List,path)
            if self.ui.comboBox_3.currentText() in filename_List:

                os.startfile(os.path.join(path , self.ui.comboBox_3.currentText() + '.grf'))
            else:
                # print("找不到相关报表")
                QMessageBox.information(self, '提示', '找不到相关报表')
        elif self.sender().objectName() == '打开报表所在位置':

            filename_List, path = self.getReportStyles()

            if self.ui.comboBox_3.currentText() in filename_List:
                filename= os.path.join(path , self.ui.comboBox_3.currentText() + '.grf')
                if os.path.isfile(filename):
                    os.system(f"explorer /select,{filename}")
                else:
                    QMessageBox.information(self, '提示', '找不到相关报表')
            else:
                QMessageBox.information(self, '提示', '找不到相关报表')
        elif self.sender().objectName() == '打印预览' or self.sender().objectName() == 'toolButton_6':
            try:
                filename_List, path = self.getReportStyles()
                # print(filename_List, path)
                if self.ui.comboBox_3.currentText() in filename_List:
                    path = os.path.join(path , self.ui.comboBox_3.currentText() + '.grf')
                    Report = client.Dispatch("gregn.GridppReport.6")  # 是com组件，engine

                    if os.path.exists(path):
                        Report.LoadFromFile(path)  # 加载打印模板
                        Report.PrepareLoadData()  # 推模式，此语句要在前面定义好，表示不用数据库的数据
                        # 创建打印数据
                        parms, fileds_items, subreport_parms, subreport_fileds_items = self.print_get_data()
                        if subreport_parms or subreport_fileds_items:
                            SubReport = Report.ControlByName("SubReport1").AsSubReport.Report  # 子报表
                            SubReport.PrepareLoadData()
                            if subreport_parms:
                                for k, v in parms.items():
                                    if v == None:
                                        v = ''
                                    SubReport.ParameterByName(k).AsString = str(v)
                            if subreport_fileds_items:
                                for subreport_fileds_item in subreport_fileds_items:
                                    SubReport.DetailGrid.Recordset.Append()  # 添加字段值的开始
                                    for k, v in subreport_fileds_item.items():
                                        if v == None:
                                            v = ''
                                        SubReport.FieldByName(k).AsString = str(v)  # 对字段赋值
                                    SubReport.DetailGrid.Recordset.Post()  # 添加字段值的结束
                        if parms or fileds_items:
                            if parms:
                                for k, v in parms.items():
                                    if v == None:
                                        v = ''
                                    Report.ParameterByName(k).AsString = str(v)
                            if fileds_items:
                                for fileds_item in fileds_items:
                                    Report.DetailGrid.Recordset.Append()  # 添加字段值的开始
                                    for k, v in fileds_item.items():
                                        if v == None:
                                            v = ''

                                        Report.FieldByName(k).AsString = str(v)  # 对字段赋值
                                    Report.DetailGrid.Recordset.Post()  # 添加字段值的结束

                        if '打印预览' in self.sender().objectName():
                            Report.PrintPreview(True)  # 打印预览
                        else:
                            Report.Print(True)  # 直接打印
                    else:
                        QMessageBox.information(self, "提示", "文件不存在，请检查打印的文件是否存在")

                else:
                    # print("找不到相关报表")
                    QMessageBox.information(self, '提示', '找不到相关报表')
            except Exception as e:
                QMessageBox.information(self, "提示", f"错误{e}")

    def print_get_data(self):
        '''打印报表所需要的数据
        parms: 参数集合
        fileds: 字段集合
        subreport_parms :子报表参数集合
        subreport_fileds:子报表字段集合
        '''
        parms, fileds_items, subreport_parms, subreport_fileds_items ={},[],{},[]
        return parms, fileds_items, subreport_parms,subreport_fileds_items
    def auto_(self):
        self.ui.tableWidget.resizeColumnsToContents()



    def page_count_Changed(self):

        self.Next_Btn_Clicked(int(self.ui.comboBox_2.currentText()) - 1, self.items)

    def page_row_Changed(self):
        self.page_row = int(self.ui.comboBox.currentText())
        self.Next_Btn_Clicked(0, self.items)
    @wrapper_progress
    def progress_working(self):
        for i in range(self.ui.tableWidget.rowCount()):
            self.ui.tableWidget.setRowHidden(i, False)
        self.ui.tableWidget.clear()
        self.ui.tableWidget.setSortingEnabled(False)

        # 设置两行间隔色
        self.ui.tableWidget.setAlternatingRowColors(True)
        sql=self.progress_working_sql()
        bool, mesg, data, fileds=self.progress_working_data(sql)
        if bool and data:

            self.ui.tableWidget.setColumnCount(len(fileds))
            self.ui.tableWidget.setRowCount(len(data))
            # 设置表头
            self.ui.tableWidget.setHorizontalHeaderLabels(fileds)

            # # 添加数据
            for i in range(len(data)):

                for j in range(len(fileds)):
                    if data[i][j] == None:
                        self.ui.tableWidget.setItem(i, j, QTableWidgetItem(''))
                    else:
                        self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(data[i][j])))

            for i in range(len(data)):
                self.ui.tableWidget.setRowHidden(i, True)
            self.currend_page = 0
            self.items = [i for i in range(self.ui.tableWidget.rowCount())]

            # 升降序排序
            self.ui.tableWidget.setSortingEnabled(True)
            # #设置列宽
            # self.ui.tableWidget.setColumnWidth(0,300)
            # 设置列宽自适应
            self.ui.tableWidget.resizeColumnsToContents()
            # 设置整行选择
            self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)

            self.Next_Btn_Clicked(0, self.items)
    def progress_working_sql(self):
        where_筛选条件 = []
        for k, v in self.search_text.items():
            if '日期' in k:
                where_筛选条件.append(f"{k} between '{v.get('开始日期')}' and  '{v.get('结束日期')}'")
            else:
                where_筛选条件.append(f"{k} like '%%{v}%%'")
        self.ui.label_5.setText(str(self.search_text))
        if where_筛选条件:
            sql = f"select * from {self.tableName} where {' and '.join(where_筛选条件)}"
        else:
            sql = f"select * from {self.tableName} "
        return sql
    def progress_working_data(self,sql=None):
        bool, mesg, data, fileds = 操作_sql().query_one(sql)
        # print(bool,data,mesg)
        return bool, mesg, data, fileds



    def 显示查询数据(self):
        self.进度条 = progress()
        self.进度条.show()
        thread1 = threading.Thread(target=self.progress_working)
        thread1.start()

    def ALL_Btn_Clicked(self, current_page, items):
        self.current_page = current_page + 1
        self.items = items
        # print(len(self.items), self.current_page)
        total_row = len(self.items)  # 所有行数
        self.page_row = total_row

        page_ = divmod(total_row, self.page_row)  # 商和余数返回（3，1）
        if page_[1] == 0:
            page_count = page_[0]
        else:
            page_count = page_[0] + 1

        if self.current_page <= 0:
            self.current_page = 1
        if self.current_page >= page_count + 1:
            self.current_page = page_count

        # 隐藏所有
        for i in range(len(self.items)):
            if i >= self.page_row * (self.current_page - 1) and i < self.page_row * (self.current_page):
                self.ui.tableWidget.setRowHidden(self.items[i], False)
            else:
                self.ui.tableWidget.setRowHidden(self.items[i], True)
        # self.ui.tableWidget.resizeColumnsToContents()
        # self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.label_2.setText(
            "第" + str(self.current_page) + "页/总" + str(page_count) + "页 共" + str(
                total_row) + "行数据 每页显示" + str(
                self.page_row) + "行数据")
        # self.page_row = 20

    def Next_Btn_Clicked(self, current_page, items):
        self.current_page = current_page + 1
        self.items = items
        # print(len(self.items), self.current_page)
        total_row = len(self.items)  # 所有行数

        page_ = divmod(total_row, self.page_row)  # 商和余数返回（3，1）
        if page_[1] == 0:
            page_count = page_[0]
        else:
            page_count = page_[0] + 1

        if self.current_page <= 0:
            self.current_page = 1
        if self.current_page >= page_count + 1:
            self.current_page = page_count

        # 隐藏所有
        for i in range(len(self.items)):
            if i >= self.page_row * (self.current_page - 1) and i < self.page_row * (self.current_page):
                self.ui.tableWidget.setRowHidden(self.items[i], False)
            else:
                self.ui.tableWidget.setRowHidden(self.items[i], True)
        # self.ui.tableWidget.resizeColumnsToContents()
        # self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        tex = f"第{self.current_page}页/总{page_count}页 共{total_row}行数据 每页显示{self.page_row}行数据"
        self.ui.label_2.setText(tex)

    def TextChanged(self):
        # self.cbxtext=self.ui.comboBox.currentText()
        # self.显示数据()
        for i in range(self.ui.tableWidget.rowCount()):
            self.ui.tableWidget.setRowHidden(i, True)
        text = self.ui.lineEdit.text()  # 筛选 含有 “test” 的所有行
        if text != "":
            items = set()
            items_all = self.ui.tableWidget.findItems(text, Qt.MatchFlag.MatchContains)

            for item in items_all:
                self.ui.tableWidget.setRowHidden(item.row(), False)
                items.add(item.row())
            self.items = list(items)

            # self.ui.tableWidget.resizeColumnsToContents()
        else:
            # items = self.ui.tableWidget.findItems("*", PyQt5.QtCore.Qt.MatchFlag.MatchWildcard)  # 基于通配符
            for i in range(self.ui.tableWidget.rowCount()):
                self.ui.tableWidget.setRowHidden(i, False)
            self.items = [i for i in range(self.ui.tableWidget.rowCount())]
            # self.ui.tableWidget.resizeColumnsToContents()
        self.Next_Btn_Clicked(0, self.items)



    def Del_Btn_Clicked(self):
        pass

    def New_Btn_Clicked(self):

        pass

    def Updata_Btn_Clicked(self):
        '''更新，检查受否存在，存在就更新'''
        pass

    def Show_Btn_Clicked(self):
        pass

    def Flash_Btn_Clicked(self):
        self.progress_working()


class 筛选条件_窗体(QWidget):
    def __init__(self,sql,curr_app_page):
        '''饮片物料信息_原料 '''
        super(筛选条件_窗体, self).__init__()
        self.curr_app_page=curr_app_page
        self.sql=sql

        self.initUi()
        self.setWindowTitle('查询条件')


    def initUi(self):
        '''窗口的初始化'''
        self.ui = 筛选条件.Ui_Form()
        self.ui.setupUi(self)
        self.初始化()
        #
        #信号与槽
        self.ui.pushButton.clicked.connect(self.close)
        self.ui.pushButton_2.clicked.connect(self.Btn_Ok_Clicked)

    def _NewtoolBtn_Clicked(self):
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(combo.sizePolicy().hasHeightForWidth())
        combo = QComboBox()  # 字段项目
        combo.setSizePolicy(sizePolicy)
        combo.setMinimumSize(QSize(0, 30))
        combo.addItems([str(k) for k in self.fileds_data_list.keys()])
        combo.setEditable(False)
        combo.currentIndexChanged.connect(self.combo_textChanged)

        hlayout = QHBoxLayout()
        hlayout.addWidget(combo)
        self.ui.verticalLayout_3.addLayout(hlayout)
        if '日期' not in combo.currentText():
            combo_2 = ExtendedComboBox()  # 查询项目
            combo_2.setSizePolicy(sizePolicy)
            combo_2.setMinimumSize(QSize(0, 30))
            combo_2.setEditable(True)

            combo_2.addItems([str(v) for v in self.fileds_data_list.get(combo.currentText())])
            combo_2.setCurrentText('全部')
            hlayout.addWidget(combo_2)

    def combo_textChanged(self):
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)

        if '日期' in self.sender().currentText():
            #找出所有子lyout
            for child in self.ui.verticalLayout_3.children():
                # print(child.itemAt(0).widget())
                # print(child.itemAt(1).widget().currentText())
                # print(child)
                if self.sender()==child.itemAt(0).widget():

                    for i in range(child.count()):
                        if i==0:
                            pass
                        else:
                            child.itemAt(i).widget().deleteLater()

                    date_edit1 = QDateEdit()

                    date_edit2=QDateEdit()
                    child.addWidget(date_edit1)
                    child.addWidget(date_edit2)
                    date_edit1.setDate(QDate.currentDate().addDays(-30))
                    date_edit2.setDate(QDate.currentDate())
                    date_edit1.setCalendarPopup(True)
                    date_edit2.setCalendarPopup(True)
                    date_edit1.setDisplayFormat("yyyy/MM/dd")
                    date_edit2.setDisplayFormat("yyyy/MM/dd")
                    break
        else:
            pass
            for child in self.ui.verticalLayout_3.children():

                if self.sender() == child.itemAt(0).widget():

                    for i in range(child.count()):
                        if i==0:
                            pass
                        else:
                            child.itemAt(i).widget().deleteLater()

                    combo_2 = ExtendedComboBox()  # 查询项目
                    combo_2.setSizePolicy(sizePolicy)
                    combo_2.setMinimumSize(QSize(0, 30))
                    combo_2.setEditable(True)
                    child.addWidget(combo_2)
                    combo_2.addItems([str(v) for v in self.fileds_data_list.get(child.itemAt(0).widget().currentText())])
                    combo_2.setCurrentText('全部')
                    break

    def 初始化(self):
        self.fileds_data_list = {}
        bool, mesg, data, fileds = 操作_sql().query_one(self.sql)
        if bool:

            for i in range(len(fileds)):
                self.fileds_data_list[fileds[i]]=set([da[i] for da in data])

        self.ui.toolButton.clicked.connect(self._NewtoolBtn_Clicked)
        self._NewtoolBtn_Clicked()
        self.ui.verticalLayout_3.children()[0].itemAt(0).widget().setCurrentText('单据日期')


    def Btn_Ok_Clicked(self):
        pass
        search_dist={}

        for child in self.ui.verticalLayout_3.children():
            # print(child.itemAt(0).widget().currentText())
            # print(child.itemAt(1).widget().currentText())
            if child.count()==2:
                if child.itemAt(1).widget().currentText()=='' or child.itemAt(1).widget().currentText()=='全部':
                    pass
                else:
                    search_dist[child.itemAt(0).widget().currentText()]=child.itemAt(1).widget().currentText()
            elif child.count()==3:

                search_dist[child.itemAt(0).widget().currentText()] = {'开始日期': child.itemAt(1).widget().date().toString('yyyy-MM-dd'),
                                                                       '结束日期':child.itemAt(2).widget().date().toString('yyyy-MM-dd')}
        # print(search_dist)

        self.curr_app_page.search_text=search_dist
        self.curr_app_page.进度条 = progress()
        self.curr_app_page.进度条.show()
        thread1 = threading.Thread(target=self.curr_app_page.progress_working)
        thread1.start()
        #
        self.close()

class 导入_显示_基类(QWidget):
    def __init__(self,window_title,data,type):
        super().__init__()
        self.window_title=window_title
        self.data=data
        self.type=type
        self.init_tableName()

        self.initUi()
        self.setWindowTitle(window_title)
    def init_tableName(self):
        self.tableName = self.window_title
    def initUi(self):
        self.ui = 基础信息导入.Ui_Form()
        self.ui.setupUi(self)
        self.ui.radioButton_2.setChecked(True)
        self.显示数据()
        self.ui.pushButton.clicked.connect(self.Btn_Clicked)

    def 显示数据(self):
        if self.type=='xlsx':
            columns = [column.value for column in self.data[0]]
            self.ui.tableWidget.setColumnCount(len(columns))
            self.ui.tableWidget.setRowCount(len(self.data)-1)
            # 设置表头
            self.ui.tableWidget.setHorizontalHeaderLabels(columns)

            # 添加数据
            for i in range(len(self.data)-1):
                for j in range(len(self.data[i+1])):
                    # print(str(self.data[i+1][j].value))
                    if self.data[i+1][j].value:
                        self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(self.data[i + 1][j].value)))
                    else:
                        self.ui.tableWidget.setItem(i, j, QTableWidgetItem(''))
        elif self.type == 'xls':
            columns = [column for column in self.data[0]]
            self.ui.tableWidget.setColumnCount(len(columns))
            self.ui.tableWidget.setRowCount(len(self.data) - 1)
            # 设置表头
            self.ui.tableWidget.setHorizontalHeaderLabels(columns)

            # 添加数据
            for i in range(len(self.data) - 1):
                for j in range(len(self.data[i + 1])):
                    # print(str(self.data[i+1][j].value))
                    if self.data[i + 1][j]:
                        self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(self.data[i + 1][j])))
                    else:
                        self.ui.tableWidget.setItem(i, j, QTableWidgetItem(''))

    def insertData(self):
        '''追加模式'''
        sql_all = []
        fileds=[]
        for i in range(self.ui.tableWidget.columnCount() - 1):
            fileds.append(self.ui.tableWidget.horizontalHeaderItem(i).text())
        字段名 = str(tuple(fileds)).replace("'", "")

        for i in range(self.ui.tableWidget.rowCount()):

            li = []
            for j in range(self.ui.tableWidget.columnCount() - 1):
                li.append(self.ui.tableWidget.item(i, j).text())

            字段值 = tuple(li)
            字段数量 = len(li)
            sql = f"insert into {self.tableName} {字段名} values ({str('%s,' * 字段数量)[:-1]})"
            sql_all.append([sql, 字段值])



        bool, mesg = 操作_sql().alt_many(sql_all)

        if bool:
            QMessageBox.information(self, "提示", "保存成功。")
            # self.parent().deleteLater()
            self.close()
        else:
            QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
    def rewriteData(self):
        sql_all = []
        reply = QMessageBox.question(self, "提示",
                                     "真的要用覆写模式吗？\n复写模式表示把之前所有的记录产品信息都删除掉不包括质量标准",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:

            sql_all.append([f'delete from {self.tableName}', ()])

            fileds = []
            for i in range(self.ui.tableWidget.columnCount() - 1):
                fileds.append(self.ui.tableWidget.horizontalHeaderItem(i).text())
            字段名 = str(tuple(fileds)).replace("'", "")

            for i in range(self.ui.tableWidget.rowCount()):
                li = []
                for j in range(self.ui.tableWidget.columnCount() - 1):
                    li.append(self.ui.tableWidget.item(i, j).text())

                字段值 = tuple(li)
                字段数量 = len(li)
                sql = f"insert into {self.tableName} {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                sql_all.append([sql, 字段值])

        bool, mesg = 操作_sql().alt_many(sql_all)
        if bool:
            QMessageBox.information(self, "提示", "保存成功。")
            self.close()
        else:
            QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
    def updateData(self):
        '''更新模式
            根据品名+批号+执行标准作为更新模式
        '''
        sql_all=[]
        fileds = []
        for i in range(self.ui.tableWidget.columnCount() - 1):
            fileds.append(self.ui.tableWidget.horizontalHeaderItem(i).text())
        字段名 = str(tuple(fileds)).replace("'", "")

        for i in range(self.ui.tableWidget.rowCount()):
            li = []
            for j in range(self.ui.tableWidget.columnCount() - 1):
                li.append(self.ui.tableWidget.item(i, j).text())

            字段值 = tuple(li)
            字段数量 = len(li)

            update_str = []
            for k, v in zip(fileds, li):
                update_str.append(f"{k}='{v}'")
            更新字段_值 = str(update_str).replace('"', '')[1:-1]
            sql = f"""insert into {self.tableName} {字段名} values ({str('%s,' * 字段数量)[:-1]})
                     on duplicate key update {更新字段_值}
                    """
            sql_all.append([sql, li])


        bool, mesg = 操作_sql().alt_many(sql_all)
        print(bool,mesg,sql_all)
        if bool:
            QMessageBox.information(self, "提示", "保存成功。")
            self.close()
            # self.parent().deleteLater()

        else:
            QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
    def Btn_Clicked(self):
        # 导入按钮
        # print('dd')
        # print(self.ui.tableWidget.horizontalHeaderItem(0).text())
        if self.ui.radioButton_2.isChecked():  # 追加模式
            self.insertData()


        elif self.ui.radioButton.isChecked():  # 覆写模式
            self.rewriteData()


        elif self.ui.radioButton_3.isChecked():  # 更新模式
            self.updateData()
            sql_all = []

if __name__=='__main__':
    app = QApplication(sys.argv)
    主窗口 = 管理窗口_基类()
    主窗口.show()

    sys.exit(app.exec())